package lormi.meipin.service.impl;


import lormi.meipin.common.Constants;
import lormi.meipin.common.LMOAuth2API;
import lormi.meipin.entity.SystemInfo;
import lormi.meipin.exception.LMException;
import lormi.meipin.service.BaseService;
import lormi.meipin.service.ISystemInfoService;
import lormi.meipin.util.CacheUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class SystemInfoService extends BaseService implements ISystemInfoService {


	@Override
	public Map<String,String> getShareText() {
		Map<String,String> map = new HashMap<>();
		map.put("share_text_1", systemInfoMapper.selectByKey("share_text_1").getSvalue());
		map.put("share_text_2", systemInfoMapper.selectByKey("share_text_2").getSvalue());
		return map;
	}

	@Override
	public Map<String, String> getVersionUpdate() {
		Map<String,String> map = new HashMap<>();
		map.put("version", systemInfoMapper.selectByKey("system_version").getSvalue());
		map.put("update_url", systemInfoMapper.selectByKey("update_url").getSvalue());
		return map;
	}

	@Override
	public SystemInfo getSystemValue(String key) {
		SystemInfo systemInfo = (SystemInfo) CacheUtil.getCacheUtil().getOtherCache("sys_"+key);
		
		if (systemInfo==null) {
			systemInfo = systemInfoMapper.selectByKey(key);
			CacheUtil.getCacheUtil().setOtherCache("sys_"+key, systemInfo);
		}
		return systemInfo;
	}

	@Override
	public SystemInfo regClient(String client) {
		if (!Constants.defaultClientKey.equals(client)){
			throw new LMException(200006);
		}
        String key = UUID.randomUUID().toString();
        String secret = LMOAuth2API.getToken().substring(0,16);
        SystemInfo systemInfo = new SystemInfo();
        systemInfo.setSkey(key);
        systemInfo.setSvalue(secret);
        systemInfo.setSdesc(Constants.defaultClientKey);
        if (systemInfoMapper.insert(systemInfo)<1){
            throw new LMException();
        }
        return systemInfo;
	}

}
